package com.cygsunri.wisdompark.callback.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cygsunri.common.CommonConstant;
import com.cygsunri.exception.BusinessException;
import com.cygsunri.response.ResultCodeEnum;
import com.cygsunri.wisdompark.bussiniss.vo.BaseDataResult;
import com.cygsunri.wisdompark.callback.service.QueryService;
import com.cygsunri.wisdompark.callback.vo.notice.MthCarInfoQueryDTO;
import com.cygsunri.wisdompark.util.CommonUtil;
import com.cygsunri.wisdompark.util.HttpUtils;
import com.cygsunri.wisdompark.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *
 * </p>
 *
 * @author cygsunri
 * @since 2021/8/17
 */
@Slf4j
@Service
public class QueryServiceImpl implements QueryService {
    @Override
    public BaseDataResult getMthCarInfo(MthCarInfoQueryDTO mthCarInfoQueryDTO) {
        //http://openapi.szymzh.com/Api/Inquire/GetMthCarInfo
        log.info("NoticeServiceImpl addMthCar ====>> "+ JSON.toJSONString(mthCarInfoQueryDTO));
        BaseDataResult result = new BaseDataResult();
        try {
            DecimalFormat df = new DecimalFormat("#.000000000");
            Random r = new Random();
            String rand = df.format(r.nextDouble() * 5);
            mthCarInfoQueryDTO.setRand(rand);
            Map<String, Object> stringObjectMap = CommonUtil.objectToMap(mthCarInfoQueryDTO);
            Map<String, Object> strObjectMap = CommonUtil.sortMapByKey(stringObjectMap);
            String urlParamsByMap = CommonUtil.getUrlParamsByMap(strObjectMap);
            String stringSignTemp=urlParamsByMap+"&"+ CommonConstant.APP_SECRET;
            String strSign = MD5Util.encrypt(stringSignTemp).toUpperCase();
            log.info("签名串 ====>> "+stringSignTemp + " Sign签名 ====>> "+strSign);
            mthCarInfoQueryDTO.setSign(strSign);
            HttpResponse response = HttpUtils.doPost("http://openapi.szymzh.com", "/Api/Inquire/GetMthCarInfo", "post", new HashMap<String, String>(),new HashMap<String, String>(),JSON.toJSONString(mthCarInfoQueryDTO));
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
                result = JSON.parseObject(json, new TypeReference<BaseDataResult>() {});
            }else{
                throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),"新增月租车通知失败,请核实!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResultCodeEnum.SYS_ERROR.getCode(),e.getMessage());
        }
        return result;

    }
}
